// pages/list/list.js../../modules/chat-input/chat-input
import * as chatInput from "../../chat/modules/chat-input/chat-input";
import IMOperator from "./im-operator";
import UI from "./ui";
import MsgManager from "./msg-manager";
const app = getApp();
/**
 * 聊天页面
 */
Page({

    /**
     * 页面的初始数据
     */
    data: {
        textMessage: '',
        chatItems: [],
        latestPlayVoicePath: '',
        isAndroid: true,
        chatStatue: 'open',
        popshow: false,
        auth:3 ,  //3为听众, 1为主持人 2为主讲人
        info: {},
        listeners: [],
        ifshowtext: false   //是否展示观众弹幕
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // let info = JSON.parse(options.info);
        this.setData({
          info: {
            id: 2
          },
          auth: 1
        })
        let room = {
            roomid: 'HR18AA9C8CE5E69FB5',
            openid: app.globalData.auth.openid
        } 
  
        this.initData();
        wx.setNavigationBarTitle({
            title: '聊天室'
        });
        this.imOperator = new IMOperator(this, room);
        this.UI = new UI(this);
        //进行登陆认证
        this.imOperator.onLoginCb({
            success: (res) => {

            },
            fail: (res) => {

            }
        });
        this.msgManager = new MsgManager(this);

        this.imOperator.onSimulateReceiveMsg((msg, cmd) => {

          msg.isMy = msg.openid === getApp().globalData.auth.openid;
          app.http.$ajax({
            url: 'v1.chat/getAuth',
            data: {
              id: this.data.info.id, //直播室id
              open_id:msg.openid,     //openid
            },
            loading: false
          }, {
            success: (res) => {
                //主持人
                msg.headUrl = res.data.avatar
                let newmsg = Object.assign(msg, res.data)
                
                if(cmd == 3) {
                  if (newmsg.isMy) {
                    return;
                  }
                  
                  this.msgManager.showMsg({msg:newmsg})
                } else if(cmd == 6) {
                  if (this.data.listeners.length >= 3) {
                    this.data.listeners.shift();
                    this.data.listeners.push(newmsg)
                  } else {
                    this.data.listeners.push(newmsg)
                  }
                  this.setData({
                    listeners: this.data.listeners
                  })
                }
            },
            fail:(res) => {

            }
          })
        });
    },

    initData() {
        let that = this;
        let systemInfo = wx.getSystemInfoSync();
        chatInput.init(this, {
            systemInfo: systemInfo,
            minVoiceTime: 1,
            maxVoiceTime: 60,
            startTimeDown: 56,
            format: 'mp3',//aac/mp3
            sendButtonBgColor: 'mediumseagreen',
            sendButtonTextColor: 'white',
            extraArr: [{
                picName: 'choose_picture',
                description: '照片'
            }, 
            {
                picName: 'take_photos',
                description: '拍摄'
            },
            {
                picName: 'close_chat',
                description: '预定义文字图片'
            }],
            // tabbarHeigth: 48
        });

        let rpxheight = ((systemInfo.windowHeight * 750) / systemInfo.windowWidth)
        let scrollHeight = rpxheight - 130
        that.setData({
            scrollHeight: scrollHeight,
            pageHeight: systemInfo.windowHeight,
            isAndroid: systemInfo.system.indexOf("Android") !== -1,
        });
        wx.setNavigationBarTitle({
            title: '聊天室'
        });  
        that.textButton();
        that.extraButton();
        that.voiceButton();
    },
    
    textButton() {
        chatInput.setTextMessageListener((e) => {
            let content = e.detail.value;
            this.msgManager.sendMsg({type: IMOperator.TextType, content});
        },);    
    },
    popSend(e) {
      let content = e.detail.content;
      let type = e.detail.type;
      let is_line = false;
      if (type == 4 || type == 5) {
        is_line = true;
      }
      this.setData({
        popshow:false  
      })
      
      this.msgManager.sendPopMsg({ type: type, content,is_line });
    },
    listenersend(e) {
      this.setData({
        ifshowtext: false
      })
      let content = e.detail.content;
      let type = e.detail.type;
      this.setData({
        popshow: false
      })

      this.imOperator.listenerSendMsg({ type: type, content });
    },
    //解决事件
    chatInputGetValueEvent : function (e) {
      chatInput.chatInputGetValueEvent(e);
    },
    
    voiceButton() {
        chatInput.recordVoiceListener((res, duration) => {
            let tempFilePath = res.tempFilePath;
            this.msgManager.sendMsg({type: IMOperator.VoiceType, content: tempFilePath, duration});
        });
        chatInput.setVoiceRecordStatusListener((status) => {
            this.msgManager.stopAllVoice();
        });
    },
    
    //模拟上传文件，注意这里的cbOk回调函数传入的参数应该是上传文件成功时返回的文件url，这里因为模拟，我直接用的savedFilePath
    simulateUploadFile({savedFilePath, duration, itemIndex, success, fail}) {
        setTimeout(() => {
            let urlFromServerWhenUploadSuccess = savedFilePath;
            success && success(urlFromServerWhenUploadSuccess);
        }, 1000);
    },
    extraButton() {
        let that = this;
        chatInput.clickExtraListener((e) => {
            let chooseIndex = parseInt(e.currentTarget.dataset.index);
            if (chooseIndex === 2) {
                that.myFun();
                return;
            }
            wx.chooseImage({
                count: 1, // 默认9
                sizeType: ['compressed'],
                sourceType: chooseIndex === 0 ? ['album'] : ['camera'],
                success: (res) => {
                    this.msgManager.sendMsg({type: IMOperator.ImageType, content: res.tempFilePaths[0]})
                }
            });
        });
    },
    /**
     * 自定义事件
     */
    myFun() {
        this.setData({
          popshow: true
        })
    },
    closepop() {
      this.setData({
        popshow: false
      });
    },
    //聊天代码
    onHide() {
        app.appIMDelegate.onHide();
    },
    //聊天代码
    onShow(options) {
        //连接聊天服务器
        let url = 'wss://39.106.192.35/ws?token=' + app.globalData.auth.token
        console.log()
        app.appIMDelegate.onShow({
          url: url
        });
    },

    resetInputStatus() {
        chatInput.closeExtraView();
    },
    ifshowtextclick(e) {
      this.setData({
        ifshowtext: e.detail.ifshowtext
      })
    },
    sendMsg({content, itemIndex, success}) {
        this.imOperator.onSimulateSendMsg({
            content,
            success: (msg) => {
              
                this.UI.updateViewWhenSendSuccess(msg, itemIndex);
                success && success(msg);
            },
            fail: () => {
                this.UI.updateViewWhenSendFailed(itemIndex);
            }
        })
    },
    /**
     * 重发消息
     * @param e
     */
    resendMsgEvent(e) {
        const itemIndex = parseInt(e.currentTarget.dataset.resendIndex);
        const item = this.data.chatItems[itemIndex];
        this.UI.updateDataWhenStartSending(item, false, false);
        this.msgManager.resend({...item, itemIndex});
    },
    
});